# -*- coding: utf-8 -*-
# owner: shenyi

from typing import Optional

from src.providers.base import BaseProvider
from src.models.instance import (
    CreateInstanceRequest,
    DeleteInstanceRequest,
    InstanceTypeRequest,
    AvailableInstanceTypeRequest,
    QueryInstanceRequest,
)
from src.models.responses import (
    CreateResponse,
    DeleteResponse,
    InstanceTypeResponse,
    AvailableZonesInstanceTypeResponse,
    InstanceType as ResponseInstanceType,
    InstanceListResponse
)
from src.core import logger
from src.strategies.strategy import ExcludeInstanceFamilyStrategy, CpuStrategy, MemoryStrategy

from .client import Client
from tencentcloud.cvm.v20170312 import models
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient


class Cvm(BaseProvider):
    """
    腾讯云 CVM 实现类
    """

    def __init__(self, **config):
        super().__init__(**config)
        # 实例属性，支持依赖注入（便于 mock 测试）
        self._client: Optional[AbstractClient] = config.get("client")

    async def create_instance(self, request: CreateInstanceRequest) -> CreateResponse:
        """
        创建 CVM 实例

        Docs: https://console.cloud.tencent.com/api/explorer?Product=cvm&Version=2017-03-12&Action=RunInstances
        """

        # 加载标签
        tags = []
        if request.tag:
            for tag in request.tag:
                tags.append({"Key": tag["key"], "Value": tag["value"]})
                
        data_disks = []
        if request.data_disk:
            for data in request.data_disk:
                size = request.request_disk_size if request.request_disk_size > data["size"] else data["size"]
                data_disks.append({"DiskSize": size, "DiskType": data["category"]})
                
        try:
            req = models.RunInstancesRequest()
            params = {
                "InstanceType": request.instance_type,
                "DataDisks": data_disks,
                "InstanceName": request.host_name,
                "HostName": request.host_name,
                "LaunchTemplate": {
                    "LaunchTemplateId": request.launch_template_id,
                    "LaunchTemplateVersion": int(request.launch_template_version)
                },
                "ImageId": request.image_id,
            }

            req.from_json_string(str(params))
            resp = self._client.RunInstances(req)
            instance_ids = resp.InstanceIdSet or []
            return CreateResponse(instance_ids=instance_ids)
        except Exception as e:
            error_msg = str(e)
            logger.exception(f"Failed to create CVM instance: {error_msg}")
            return CreateResponse(status_code=500, message=error_msg)

    async def delete_instance(self, request: DeleteInstanceRequest) -> DeleteResponse:
        """
        删除 CVM 实例

        Docs: https://console.cloud.tencent.com/api/explorer?Product=cvm&Version=2017-03-12&Action=TerminateInstances
        """

        try:
            req = models.TerminateInstancesRequest()
            params = {
                "InstanceIds": [request.instance_id],
                "ReleasePrepaidDataDisks": True
            }
            req.from_json_string(str(params))

            self._client.TerminateInstances(req)
            return DeleteResponse(status_code=200, message="success")
        except TencentCloudSDKException as e:
            logger.exception(f"Failed to delete CVM instance {request.instance_id}: {str(e)}")
            if e.code == "InvalidInstanceId.NotFound":
                status_code = 404
            else:
                status_code = 500
            return DeleteResponse(status_code=status_code, message=str(e))
        except Exception as e:
            error_msg = str(e)
            logger.exception(f"Failed to delete CVM instance {request.instance_id}: {error_msg}")
            return DeleteResponse(status_code=500, message=error_msg)

    async def list_instance_types(self, request: InstanceTypeRequest) -> InstanceTypeResponse:
        """
        查询实例规格列表

        Docs: https://console.cloud.tencent.com/api/explorer?Product=cvm&Version=2017-03-12&Action=DescribeZoneInstanceConfigInfos
        """

        filters = [
            {
                "Name": "instance-charge-type",
                "Values": ["POSTPAID_BY_HOUR"],
            }
        ]
        if request.zone_id:
            filters.append({
                "Name": "zone",
                "Values": [request.zone_id]
            })
            
        try:
            req = models.DescribeInstanceTypeConfigsRequest()
            params = {
                "Filters": filters
            }
            req.from_json_string(str(params))

            resp = self._client.DescribeZoneInstanceConfigInfos(req)
            instance_type_list = resp.InstanceTypeQuotaSet or []
            
            filtered_specs = []
            for instance_type in instance_type_list:
                # 应用CPU和内存过滤策略
                if CpuStrategy.filter(instance_type.Cpu, request.mini_cpu_count) or \
                   MemoryStrategy.filter(instance_type.Memory, request.mini_memory_size):
                    continue

                instance_family = instance_type.InstanceFamily
                # 过滤cpu架构 ARM架构实例：标准型SR1、标准型SK1 x86架构实例：SA系列（使用AMD EPYC处理器）以及其他大多数常见机型
                if instance_family in ["SR1", "SK1"]:
                    cpu_architecture = "arm"
                else:
                    cpu_architecture = "x86"

                if request.cpu_architecture.lower() != cpu_architecture:
                    continue

                # 实例是否售卖。取值范围：SELL：表示实例可购买 SOLD_OUT：表示实例已售罄。
                if instance_type.Status == "SOLD_OUT":
                    continue

                # 应用排除族策略
                if request.exclude_families and ExcludeInstanceFamilyStrategy.exclude(
                    instance_type.InstanceType, request.exclude_families
                ):
                    continue

                filtered_specs.append(ResponseInstanceType(
                    instance_type_id=instance_type.InstanceType,
                    cpu_core_count=instance_type.Cpu,
                    memory_size=instance_type.Memory,
                    cpu_architecture=cpu_architecture
                ))
                
            return InstanceTypeResponse(status_code=200, message="success", instance_spec=filtered_specs)
        except Exception as e:
            error_msg = str(e)
            logger.exception(f"Failed to list CVM instance types: {error_msg}")
            return InstanceTypeResponse(status_code=500, message=error_msg, instance_spec=[])
        
    async def list_available_instance_types(self, request: AvailableInstanceTypeRequest) -> AvailableZonesInstanceTypeResponse:
        """
        获取可用的机型
        
        Docs: https://console.cloud.tencent.com/api/explorer?Product=cvm&Version=2017-03-12&Action=DescribeInstanceTypeConfigs
        """
        
        # 这里可以实现获取可用实例类型的逻辑
        return AvailableZonesInstanceTypeResponse(status_code=200, message="success", instance_spec=[])
    
    async def health_check(self) -> bool:
        """
        检查 CVM 服务是否可用
        """
        return True
    
    async def list_instances(self, request: QueryInstanceRequest) -> InstanceListResponse:
        """
        查询 CVM 实例列表
        """
        return await super().list_instances(request)